package com.ruoyi.lvlian.controller;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.http.HttpHeaders;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.DriverInfo;
import com.ruoyi.lvlian.domain.Kaifangqian;
import com.ruoyi.lvlian.dto.ContractInfoDto;
import com.ruoyi.lvlian.dto.ContractInfoDto1;
import com.ruoyi.lvlian.service.ICommonService;
import com.ruoyi.lvlian.util.ContactNumGenerator;
import com.ruoyi.lvlian.util.OrderNumberGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.client.methods.HttpGet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.lvlian.domain.ContractInfo;
import com.ruoyi.lvlian.service.IContractInfoService;
import com.ruoyi.lvlian.service.IKaifangqianService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.lvlian.util.JsonFileReaderUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 合同信息Controller
 *
 * @author liyuxi
 * @date 2024-07-22
 */
@Api(value = "合同信息", tags = "合同信息Controller")
@RestController
@RequestMapping("/contractInfo")
public class ContractInfoController extends BaseController {
    @Autowired
    private IContractInfoService contractInfoService;

    @Autowired
    private IKaifangqianService kaifangqianService;


    @Autowired
    private ICommonService iCommonService;

    /**
     * 查询合同信息列表
     */
    //@RequiresPermissions("lvlian:contractInfo:list")
    @GetMapping("/list")
    public R<TableDataInfo> list(ContractInfoDto contractInfo) {

        if (SecurityUtils.getUserId() == 1) {
            contractInfo.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        } else {
            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());

            if ((Objects.isNull(contractInfo.getOrgCodes()) || contractInfo.getOrgCodes().isEmpty()) && Objects.isNull(orgCodes)) {
                return R.fail("暂未分配账本");
            }
            if (Objects.isNull(contractInfo.getOrgCodes()) || contractInfo.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                contractInfo.setOrgCodes(orgCodes);
            }
        }


        startPage();

        List<ContractInfo> list = contractInfoService.selectContractInfoList(contractInfo);
        if (list.size() > 599) {
            return R.fail("分页数目太大");
        }
        return R.ok(getDataTable(list));
    }

    /**
     * 导出合同信息列表
     */
/*    //@RequiresPermissions("lvlian:contractInfo:export")
    @Log(title = "合同信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractInfo contractInfo) {
        List<ContractInfo> list = contractInfoService.selectContractInfoList(contractInfo);
        ExcelUtil<ContractInfo> util = new ExcelUtil<ContractInfo>(ContractInfo.class);
        util.exportExcel(response, list, "合同信息数据");
    }*/

    /**
     * 获取合同信息详细信息
     */
    //@RequiresPermissions("lvlian:contractInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(contractInfoService.selectContractInfoById(id));
    }

    /**
     * 新增合同信息
     */
/*    //@RequiresPermissions("lvlian:contractInfo:add")
    @Log(title = "合同信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContractInfo contractInfo) {
        return toAjax(contractInfoService.insertContractInfo(contractInfo));
    }*/
    private String validateInData(ContractInfo contractInfo) {
        if (StringUtils.isEmpty(contractInfo.getBuyerCompanyName()) || StringUtils.isEmpty(contractInfo.getSellerCompanyName())) {
            return "购买方或销售方不能为空";
        }
        return "success";
    }

    @ApiOperation("修改合同信息")
//    //@RequiresPermissions("lvlian:contractInfo:edit")
    @Log(title = "合同信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated ContractInfo contractInfo) {
        if (!"success".equalsIgnoreCase(validateInData(contractInfo))) {
            return error(validateInData(contractInfo));
        }
        return toAjax(contractInfoService.updateContractInfo(contractInfo));
    }

    /**
     * 删除合同信息
     */
    @Log(title = "删除合同信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody String[] ids) {
        if (ids == null || ids.length == 0) {
            return error("未选中");
        }
        return toAjax(contractInfoService.deleteContractInfoByIds(ids));
    }

    @ApiOperation("导入合同信息")
    @PostMapping("/importInfo")
    public AjaxResult importInfo(MultipartFile file) {
        // 获取到批量导入的数据集合
        List<ContractInfo> dtoList = null;
        String msg = "";
        try {
            dtoList = contractInfoService.importInfo(file, "合同信息", 3);
            int totalSussess = contractInfoService.bachSave(dtoList);
            int total = dtoList.size();


            if (Math.abs(totalSussess) > total) {
                totalSussess = total;
            }
            int totalFail = total - totalSussess;
            msg = "解析到" + total + "条数据，" + "导入成功" + totalSussess + "条，导入失败" + totalFail + "条！";
        } catch (MysqlDataTruncation e) {
            e.printStackTrace();
            return success("数据错误");
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains("Incorrect date")) {
                return success("日期填写错误");
            }
            return success("模板错误");
        }


        return success(msg);
    }

    @Autowired
    private JsonFileReaderUtil jsonReader;


    @ApiOperation("发起签署")
    @PostMapping("/draft")
    public String createDraftContract(@RequestBody @Validated ContractInfoDto1 contractInfo) {
        String url = "http://121.40.250.100/resrun-paas/kaifangqian/openAPI/V2/contract/draft";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 1. 读取JSON文件内容
            // 测试场景2：解析JSON为Jackson的JsonNode对象（通用解析）
            JsonNode jsonNode = jsonReader.readJsonFile("request.json", JsonNode.class);


            // 获取signTemplateParamList数组的第一个元素（因为它是数组）
            JsonNode signTemplateParam = jsonNode.get("signTemplateParamList").get(0);

            // 获取templateParamList数组
            JsonNode templateParamList = signTemplateParam.get("templateParamList");
            if (templateParamList.isArray()) {
                // 转换为ArrayNode以便添加新元素
                ArrayNode arrayNode = (ArrayNode) templateParamList;
                ObjectMapper mapper = new ObjectMapper();

                ObjectNode buyerCode = mapper.createObjectNode();
                buyerCode.put("paramKey", "buyerCode");
                buyerCode.put("paramValue", contractInfo.getBuyerCode());
                arrayNode.add(buyerCode);


                ObjectNode buyerCompanyName = mapper.createObjectNode();
                buyerCompanyName.put("paramKey", "buyerCompanyName");
                buyerCompanyName.put("paramValue", contractInfo.getBuyerCompanyName());
                arrayNode.add(buyerCompanyName);

                ObjectNode sellerName = mapper.createObjectNode();
                sellerName.put("paramKey", "sellerName");
                sellerName.put("paramValue", contractInfo.getSellerName());
                arrayNode.add(sellerName);

                ObjectNode sellerCode = mapper.createObjectNode();
                sellerCode.put("paramKey", "sellerCode");
                sellerCode.put("paramValue", contractInfo.getSellerCode());
                arrayNode.add(sellerCode);

                ObjectNode sellerPhone = mapper.createObjectNode();
                sellerPhone.put("paramKey", "sellerPhone");
                sellerPhone.put("paramValue", contractInfo.getSellerPhone());
                arrayNode.add(sellerPhone);


                arrayNode.add(sellerName);


                ObjectNode openBank = mapper.createObjectNode();
                openBank.put("paramKey", "openBank");
                openBank.put("paramValue", contractInfo.getOpenBank());
                arrayNode.add(openBank);

                ObjectNode bankAccno = mapper.createObjectNode();
                bankAccno.put("paramKey", "bankAccno");
                bankAccno.put("paramValue", contractInfo.getBankAccno());
                arrayNode.add(bankAccno);


                ObjectNode startDate = mapper.createObjectNode();
                startDate.put("paramKey", "startDate");
                startDate.put("paramValue", contractInfo.getStartDate());
                arrayNode.add(startDate);

                ObjectNode endDate = mapper.createObjectNode();
                endDate.put("paramKey", "endDate");
                endDate.put("paramValue", contractInfo.getEndDate());
                arrayNode.add(endDate);


                // 创建要添加的新参数对象
                ObjectNode contractNum = mapper.createObjectNode();
                contractNum.put("paramKey", "contractNum");
                contractNum.put("paramValue", contractInfo.getContractNum());
                arrayNode.add(contractNum);


            }


            // 修改receiver信息
            JsonNode receiverNode = jsonNode.path("signerList").get(0).path("receiver");
            if (receiverNode.isObject()) {
                ObjectNode receiver = (ObjectNode) receiverNode;
                receiver.put("name", contractInfo.getSellerName());
                receiver.put("contact", contractInfo.getSellerPhone());
            }


            System.out.println("\n=== JSON文件内容（解析为JsonNode）===");
            System.out.println(jsonNode.toPrettyString());

            // 2. 创建POST请求
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json; charset=UTF-8");  // Add charset here
            post.setHeader("Accept", "application/json");
//防止乱码产生

            StringEntity entity = new StringEntity(jsonNode.toString(), StandardCharsets.UTF_8);
            post.setEntity(entity);


            // 3. 执行请求并获取响应
            HttpResponse response = httpClient.execute(post);
            String responseBody = EntityUtils.toString(response.getEntity());

            System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
            System.out.println("Response: " + responseBody);

            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred: " + e.getMessage();
        }
    }

    @ApiOperation("获取合同短链接")
    @GetMapping("/pageUrl")
    public String getContractPageUrl(
            @RequestParam(required = true) @ApiParam(value = "生成的合同id", required = true, example = "ff808081975dc9950197c0731bb905d5") String contractId,
            @RequestParam(required = true) @ApiParam(value = "token", required = true, example = "W89FUDDR") String appAuthToken,
            @RequestParam(required = true) @ApiParam(value = "签署环节中传购买方的甲方的电话", required = true, example = "13791273388") String contact,
            @RequestParam(required = true) @ApiParam(value = "绿链生成的合同编号", required = true) String contractNum) {
        String url = "";
        appAuthToken = "EE7TJN1E";
        try {
//保存签章信息
            Kaifangqian kaifangqian = new Kaifangqian();
            kaifangqian.setUniqueCode(OrderNumberGenerator.generateOrderNumber());
            kaifangqian.setContractId(contractId);
            kaifangqian.setAppAuthToken(appAuthToken);
            kaifangqian.setContact(contact);
            kaifangqian.setContractNum(contractNum);
            kaifangqian.setCreateUser(SecurityUtils.getUsername());
            kaifangqian.setCreateDate(DateUtils.getCurrentTime());
            kaifangqian.setId(MD5Utils.md5(contractNum));
            kaifangqianService.insertKaifangqian(kaifangqian);

            // Build the URL with parameters
            url = "http://121.40.250.100/resrun-paas/kaifangqian/openAPI/V2/contract/pageUrl?uniqueCode=" + kaifangqian.getUniqueCode() + "&appAuthToken=" + appAuthToken + "&contractId=" + contractId + "&taskId&contact=" + contact + "&partyName&noLogin=1&pageUrlExpireTime";
            System.out.println("请求链接  === " + url);

        } catch (Exception e) {
            e.printStackTrace();
        }
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Create GET request
            HttpGet get = new HttpGet(url);
            System.out.println(url);
            // Add headers (similar to your draft method)
            get.setHeader("Content-Type", "application/json; charset=UTF-8");  // Add charset here


            get.setHeader("Accept", "application/json");
            get.setHeader("sign", ""); // Add your sign header here

            // Execute request
            HttpResponse response = httpClient.execute(get);
            String responseBody = EntityUtils.toString(response.getEntity());

            System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
            System.out.println("Response: " + responseBody);

            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred: " + e.getMessage();
        }
    }


    @GetMapping("/downloadContract")
    public AjaxResult downloadContract(
            @RequestParam(required = true) @ApiParam(value = "绿链生成的合同编号", required = true) String contractNum) throws IOException {

        // 生成唯一标识符
        Kaifangqian kaifang = kaifangqianService.queryKaifangqianByContractNum(contractNum);
        // 构建带参数的URL
        String url = String.format("http://121.40.250.100/resrun-paas/kaifangqian/openAPI/V2/contract/document/download" +
                        "?appAuthToken=%s" +
                        "&uniqueCode=%s" +
                        "&contact=%s" +
                        "&contractId=%s",
                kaifang.getAppAuthToken(), kaifang.getUniqueCode(), kaifang.getContact(), kaifang.getContractId());
        return success(url);
    }

    @ApiOperation("回调方法")
    @PostMapping("/receiveResult")
    public String receiveResult() {


   /*     // 2. 验证签名
        if (!verifySignature(notification)) {
            throw new SecurityException("Invalid signature");
        }

        // 3. 处理业务逻辑
        processNotification(notification);*/

        // 4. 返回success
        return "success";
    }

    //https://data.lvlianhengsheng.com/dev-api/lvlian/contractInfo/callback
    @ApiOperation("get回调方法")
    @GetMapping("/callback")
    public ApiResponse callback() {
        ApiResponse response = new ApiResponse();
        response.setCode("200");
        response.setMessage("Success");
        return response;
    }

    public class ApiResponse {
        private String code;
        private String message;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }
}



 /*

   signReId  业务线的  a0833f16-f25c-4b49-8814-6244e50df89e  93423991-1c41-4f19-a0df-c0f599d02150
templateId 模板的   28e1a425-9d24-46ff-a332-6045f3c73794

    {
          "paramKey": "buyerCompanyName",
          "paramValue": "公司名称"
        },
        {
          "paramKey": "sellerName",
          "paramValue": "乙方"
        },
        {
          "paramKey": "sellerCode",
          "paramValue": "身份证号码"
        },
        {
          "paramKey": "sellerPhone",
          "paramValue": "手机号码"
        },
        {
          "paramKey": "sellerName",
          "paramValue": "乙方收款人名称"
        },
        {
          "paramKey": "openBank",
          "paramValue": "开户行"
        },
        {
          "paramKey": "bankAccno",
          "paramValue": "账号"
        },
        {
          "paramKey": "contractNum",
          "paramValue": "合同编号"
        },
        {
          "paramKey": "startDate",
          "paramValue": "合同生效日期"
        },
        {
          "paramKey": "endDate",
          "paramValue": "合同失效日期"
        }*/


/***
 *https://kaifangqian-platform.apifox.cn/api-209231085
 * https://kaifangqian-platform.apifox.cn/
 * https://www.yuque.com/huxin-ch41t/kaifangqian/nk2u94pue05h703z#f39eb520
 */